"""
Make console debugging output look nicer on linux! Since windows developers
can't even add ANSI color escapes to work this will be for users of proper 
Operating Systems only.
"""
import re
from utils import constants
from utils.compat import es

#===============================================================================
# Colors & Attributes
#===============================================================================
RESET       = 0
BRIGHT      = 1
DIM         = 2
UNDERLINE   = 3
BLINK       = 5
REVERSE     = 7
HIDDEN      = 8
BLACK       = 30
RED         = 31
GREEN       = 32
YELLOW      = 33
BLUE        = 34
MAGENTA     = 35
CYAN        = 36
WHITE       = 37

#===============================================================================
# Helpers
#===============================================================================

def getitems(match):
    """
    Format a match groupdict to be easier to use in the TerminalFormatter
    """
    gd = match.groupdict()
    rgd = dict(zip(gd.values(), gd.keys()))
    gs = match.groups()
    items = []
    for group in gs:
        items.append((rgd[group], group))
    return items

def color(attr, fg=None, bg=None):
    """
    Turn attributes and colors into the correct code.
    """
    if fg and bg:
        return '\033[%s;%s;%sm' % (attr, fg, bg + 10)
    elif fg:
        return '\033[%s;%sm' % (attr, fg)
    else:
        return '\033[%sm' % attr
    
#===============================================================================
# TerminalFormatter
#===============================================================================

class TerminalFormatter(object):
    """
    A terminal formatter class to format messages sent to a terminal.
    """
    def __init__(self, patterns=[], rules={}):
        """
        @param patterns: A list of compiled regular expressions. These will be
            used to format messages
        @param rules: Rules for groups in the regular expressions
        """
        self.rules      = rules
        self.patterns   = [self._compile(pat) for pat in patterns]
        self.enabled    = constants.operating_system == 'linux'
        
    def add_rule(self, groupname, attribute=RESET, fg_color=None,
                 bg_color=None):
        """
        @param groupname: The name of the group in the regular expression to
            add the rules for.
        @param attribute: Attribute to set (eg BRIGHT)
        @param fg_color: Foreground color (eg RED)
        @param bg_color: Background color (eg BLUE)
        """
        self.rules[groupname] = filter(lambda x: isinstance(x, int),
                                       [attribute, fg_color, bg_color])

    def add_pattern(self, regexp):
        """
        @param regexp: Regular expression to add
        """
        self.patterns.append(self._compile(regexp))
        
    def _compile(self, pattern):
        if isinstance(pattern, basestring):
            return re.compile(pattern)
        return pattern
    
    def _highlight(self, items):
        """
        INTERNAL
        Highlight a sequence of items
        """
        buf = ''
        for key, value in items:
            buf += color(*self.rules[key])
            buf += value
        buf += color(RESET)
        return buf
    
    def format(self, line):
        """
        Format a line if any patterns match
        """
        if self.enabled:
            for pat in self.patterns:
                match = pat.match(line)
                if match:
                    return self._highlight(getitems(match))
        return line
    
    def dbgmsg(self, level, msg):
        """
        Shortcut for es.dbgmsg(level, TerminalFormatter().format(line))
        """
        es.dbgmsg(level, self.format(msg))